﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Management.Automation;
using System.Collections;
using Google.API.Search;
using System.Windows.Forms;

namespace Gnc.SearchGoogle
	{
	[Cmdlet( VerbsCommon.Get, "GoogleResults", DefaultParameterSetName = "Search" )]
	public class GetGoogleResults : PSCmdlet
		{
		private static List<GoogleResult> s_results = new List<GoogleResult>();
		private static int s_resultIndex;

		public GetGoogleResults()
			{
			this.MaxResults = 10;
			}

		protected override void BeginProcessing()
			{
			s_resultIndex = 1;
			}

		protected override void ProcessRecord()
			{
			switch ( this.ParameterSetName )
				{
				case "Search":
					WriteVerbose( String.Format( @"Searching for ""{0}""", this.Query ) );
					s_results = new List<GoogleResult>();
					IList<IWebResult> results = GwebSearcher.Search( this.Query, this.MaxResults );
					if ( results.Count == 0 )
						{
						WriteWarning( "No results found." );
						}
					else
						{
						foreach ( IWebResult result in results )
							{
							GoogleResult googleResult = new GoogleResult( s_resultIndex++, result );
							WriteObject( googleResult );
							s_results.Add( googleResult );
							}
						}
					break;

				case "GotoResult":
					foreach ( GoogleResult googleResult in s_results )
						{
						if ( googleResult.Index == this.GotoResult )
							{
							Help.ShowHelp( null, googleResult.Url );
							return;
							}
						}
					throw new Exception( String.Format( "Result index {0} not available", this.GotoResult ) );
				}
			}

		[Parameter( ParameterSetName = "Search", Position = 0, ValueFromRemainingArguments = true )]
		public string[] QueryStrings { get; set; }

		private string Query
			{
			get
				{
				return String.Join( " ", QueryStrings );
				}
			}

		[Parameter( ParameterSetName = "Search" )]
		public int MaxResults { get; set; }

		[Parameter( ParameterSetName = "GotoResult", Mandatory = true )]
		public int GotoResult { get; set; }
		}

	public class GoogleResult
		{
		public GoogleResult( int resultIndex, IWebResult result )
			{
			this.Result = result;
			this.Index = resultIndex;
			this.Title = result.Title;
			this.VisibleUrl = result.VisibleUrl;
			this.Url = result.Url;
			this.Content = result.Content;
			this.CacheUrl = result.CacheUrl;
			}

		public int Index { get; set; }
		public string Title { get; set; }
		public string VisibleUrl { get; set; }
		public string Url { get; set; }
		public string Content { get; set; }
		public string CacheUrl { get; set; }
		IWebResult Result { get; set; }
		}
	}
